package com.syl.ippool.threadtoos.runs;

import com.syl.ippool.domain.IpBasePojo;
import com.syl.ippool.ifice.pool.IGraspIpPool;
import com.syl.ippool.utils.IpUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * 检测ip是否有效的Runnabled
 */
@Slf4j
public class CheckIpRunnable implements Runnable{

    // 需要检测的ip集合
    public List<IpBasePojo> ipBasePojoList = null;

    // ip池
    public volatile IGraspIpPool graspIpPool = null;

    public CheckIpRunnable(List<IpBasePojo> ipBasePojoList, IGraspIpPool graspIpPool) {
        this.ipBasePojoList = ipBasePojoList;
        this.graspIpPool = graspIpPool;
    }



    @Override
    public void run() {
        if (ipBasePojoList == null || ipBasePojoList.size() == 0) {
            log.error("检测ip线程任务异常，集合为0");
            return;
        }

        for (IpBasePojo basePojo : ipBasePojoList) {
            try {
                boolean valid = IpUtils.isValid(basePojo);
                if (valid) {
                    basePojo.setActive(true);
                    graspIpPool.add(basePojo);
                    log.info(basePojo.toString()+"--ip是有效ip");
                }
            } catch (Exception e) {
                basePojo.setActive(false);
                log.info(basePojo.getIp()+":"+basePojo.getPort()+"--ip无效已删除");
            }
        }

    }
}
